<?php
/*
класс-прослойка, от которого наследуются контроллеры модулей  
*/
class BasicModulController extends Controller {

    public $widget_inputdata_arr;
    public $model;
    public $view;
    public $action; // имя метода-точки входа     
    public $modul_obj;     
    public $firephp;
    public $registry;
    public $virtual_modul_index;
    public $modul_index;

    protected $sections_arr;
     protected $modul_id;
    
    private $basic_act_param;
    private $life_modul_index;
    private $grid_config = null;

    function __construct(){

        $this->registry = Registry::getInstance();

        $this->virtual_modul_index = $this->registry->virtual_modul_index;
        $this->modul_index = $this->registry->modul_index;

        defined('MODUL') ||
          define('MODUL',$this->registry->get('modul_index')); // Face
        defined('MODUL_INDEX') ||
                    define('MODUL_INDEX',strtolower( MODUL)); //face
                    
        require_once PUBLIC_PATH."/Moduls/".MODUL."/".MODUL.".php";
        require_once PUBLIC_PATH."/Moduls/".MODUL."/view.".MODUL.".php";

        $this->modul_id = $this->getModulIdByIndex(MODUL_INDEX);
        //$this->firephp = $registry->get('firephp');

        $this->modul_index = $this->registry->get('modul_index');

        // User
        $user_logged = User::isUserLogged();

        // инициализация модели
        $model_classname =   $this->modul_index;
        $this->model = new $model_classname;

        // инициализация представления
        $view_classname =   $this->modul_index . "View";
        $this->view = new $view_classname($this->modul_id);
        $this->registry->set('modul_view', $this->view);

        // родительское представление
        $this->global_view = $this->view->getView();

        //
        self::$instance = $this;

        
    }

    function getHtml(){
        return $this->html;
    }
   
    /*
     * Загружает субсекции модуля
     */
    function getSections(){
        $modul_id =  $this->getModulIdByIndex(Registry::getInstance()->get('modul_index'));  
          
        $q = "SELECT * FROM sections   
              WHERE modul_id = $modul_id ";
        $r = mysql_query($q);
        if(!$r) return false;
        if( mysql_num_rows($r) > 0){
          while($row = mysql_fetch_assoc($r)){
               $row['edit_link'] = '';
               $row['class_name'] = $this->model->translit( $row['seo_link'] );
               $row['class_name'] = preg_replace('/_/i','',$row['class_name']);
               $row['class_name'] = preg_replace('/\s/i','',$row['class_name']);
              if(User::isAdmin()) $row['edit_link'] = '/' . strtolower(Registry::getInstance()->get('modul_index')) .'/'. $row['seo_link'] .'/'. 'edit'; // /tour/photo/edit
              
              $sections[] = $row;
          } 
          return   $sections;
        }   
        
        return false;
    }
    
    function getModulIdByIndex($modul_index){
        $modul_index = strtolower($modul_index);
    
        $q = "SELECT * FROM  moduls  
              WHERE modul_index = '$modul_index' ";
        $r = mysql_query($q);
        if(!$r) return false;
        if( mysql_num_rows($r) > 0){
      
          $modul_info = mysql_fetch_assoc($r);
          
          return $modul_info['id_modul'] ;
        } 
        
        return false;
    } // -- 

    /*
    * Статические методы
    */
    
    static function getInstance(){
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    } // --

    static function action(){
        $obj = static::getInstance();
        $method = $obj->action;

        $method = preg_replace('/[-_]/i','',$method);

        if( !method_exists($obj, $method) ) throw new Exception('No action exists' . "[$method]");

        try {
            if(in_array($method,get_class_methods($obj))){
                $obj->$method();
            } else 
              throw new Exception("Не возможно вызвать метод [$method]");
        } catch(Exception $e){
            //TODO записать в лог
            // редирект убрать в другое место (коллектор ошибок)
            fb($e->getMessage());
        }
    }


    
    
    function sectionLoader(){

        static::router($this->registry->get('section_id'));
         
    }
    
    function loadMethod($method){  
    //
       // return eval("return \$this->modul->".$method."();");
       // return eval("return \$this->".$MD."();");
       // die(var_dump('aaaa'));
       // static::action();
    } // -- loadMethod
    
    public  function load(){  
        //  [!] рабочий
        try {

            static::action();

        } catch(Exception $e){
            fb($e -> getMessage());
            Registry::getInstance() -> set('error404', true);
        }
        //$this->modul_obj = static::getInstance(); die(var_dump(__CLASS__));
        //var_dump( $this->modul_obj);
        //eval("return \$this->modul_obj->".$method."();");


    } // --

    function getGridModel($filename, $root = null){
        $modul = Registry::getInstance()->modul_index;

        $data = $this->model->getColModel($modul, $filename, $root);

        if(isset($data[$filename . '_grid'])){
           return $data[$filename . '_grid'];
        }
        else return $data;
    }

    function getColModel($filename, $root = null){

        if($this->grid_config === null) $this->grid_config = $this->getGridModel($filename, $root);

        if(isset($this->grid_config['column']))
            return $this->grid_config['column'];
        else
            return $this->grid_config;
    }

    function getGridConfig($filename, $root = null){

        if($this->grid_config === null) $this->grid_config = $this->getGridModel($filename, $root);

        if(isset($this->grid_config['config']['values']))
            return $this->grid_config['config']['values'];
        else{
            if(isset($this->grid_config['config']))
                return $this->grid_config['config'];
            else
                return $this->grid_config;
        }
    }


    
} // -- BasicModulController